<?php
/**
 * Created by PhpStorm.
 * User: user
 * Date: 18-7-15
 * Time: 下午9:25
 */
class CommPrice
{
    private $fck;
    private $fee;
    private $type;
    private $getPriceFck;   //获奖者的fck，需要设置
    private $Fck;   //D('Fck')
    private $base_money;   //D('Fck')

    public function __construct($idOrRs) {
        $this->initFck($idOrRs);
        $this->initFee();
    }

    private function initFck($idOrRs) {
        $this->Fck = D('Fck');
        if(!is_numeric($idOrRs)) {
            $this->fck = $idOrRs;
        } else {
            $this->fck = D('Fck')->where(['id' => $idOrRs])->find();
        }
    }
    private function initFee() {
        $this->fee = $this->getFeeRule();
    }

    /**
     * 练手五的奖金发放中心
     * @param $rs
     * @param $type
     */
    public function priceSendCenter($type=['0'], $base_money=0) {
        if($base_money > 0) $this->base_money = $base_money;

        if(!is_array($type)) $type=array($type);

        //$this->Fck->addDan($rs['p_path'],$rs['treeplace'],$rs['u_level']); //添加单数到链上

        foreach ($type as $t) {
            $this->type = $t;
            switch ($t) {
                case 1:
                    $this->priceMeetPoint();
                    break;
                case 2:
                    $this->priceRecommDiff();
                    break;
                case 3:
                    $this->priceMeetPointLive();
                    break;
                case 4:
                    //升级发奖，级差
                    $this->priceRecommDiffLive();
                    break;
                default:
                    break;
            }
        }
    }

    private function awardCalculate($money, $ratio=100, $priceFck=null, $remark='奖', $action='') {
        $priceFck = !isset($priceFck) ? $this->getPriceFck : $priceFck;
        if(empty($priceFck) || !$priceFck) {
            $this->error('没有得奖用户');
            exit;
        }
        $price = bcmul($money, $ratio/100, 2);
        if($price <= 0) return false;

        A('Common')->zijin_log($priceFck['id'],$priceFck['user_id'], $action,
            "{$remark}", $price,"agent_use");
        $this->award_bonus($priceFck['id'], $this->fck['user_id'], $this->type, $price);
    }

    /**
     *见点奖的 T8724
     * 见点奖拿的是什么奖的基础
     */
    public function priceMeetPoint() {
        $mypath         = $this->fck['p_path'];
        $my_p_level     = $this->fck['p_level'];
        $max_plevel     = max($this->fee['s22']);
        $price_level    = $this->fee['s22'];  //获奖的各个层
        $ratio          = $this->fee['s21']; //见点奖比率

        $all_rs = M('fck')->where("id in (0{$mypath}0) AND {$my_p_level} - p_level  < {$max_plevel}")->order('p_level desc,pdt desc')->select();
        foreach ($all_rs as $rs) {
            if($my_p_level - $rs['p_level'] > $price_level[$rs['u_level'] - 1]) continue;

            $this->getPriceFck = $rs;

            $remark = '见点奖';
            $action = 'meetpoint';
            $this->awardCalculate($this->base_money, $ratio,$rs, $remark, $action);
        }
    }

    /**
     *见点奖的 T8724
     * 见点奖升级补发一次
     */
    public function priceMeetPointLive() {
        $mypath         = $this->fck['p_path'];
        $my_p_level     = $this->fck['p_level'];
        $max_plevel     = max($this->fee['s22']);
        $price_level    = $this->fee['s22'];  //获奖的各个层
        $ratio          = $this->fee['s21']; //见点奖比率

        $all_rs = M('fck')->where("id in (0{$mypath}0) AND {$my_p_level} - p_level  < {$max_plevel}")->order('p_level desc,pdt desc')->select();
        foreach ($all_rs as $rs) {
            if($my_p_level - $rs['p_level'] > $price_level[$rs['u_level'] - 1]) continue;

            $this->getPriceFck = $rs;

            $remark = '见点奖加单补发';
            $action = 'meetpoint';
            $this->type = 1;    //放到见点奖
            $this->awardCalculate($this->base_money, $ratio,$rs, $remark, $action);
        }
    }

    /**
     *见点奖的 T8724
     * 见点奖拿的是什么奖的基础
     */
    public function priceRecommDiff() {
        $my_repath = $this->fck['re_path'];
        $diff_level_ratio =  $this->fee['s23'];  //获奖的各个层

        $all_rs = M('fck')->where("id in (0{$my_repath}0)")->order('re_level desc,pdt desc')->select();
        foreach ($all_rs as $rs) {
            $ratio = $this->getReLevelRatio($diff_level_ratio, $rs['re_nums']);
            $this->getPriceFck = $rs;

            $remark = '直荐级差奖';
            $action = 'recomm';
            $this->awardCalculate($this->base_money, $ratio, $rs, $remark, $action);
        }
    }

    /**
     * 直荐级差奖 的补发 ，按照原来的奖得分，之前没有得奖的，新的不发
     * 见点奖拿的是什么奖的基础
     */
    public function priceRecommDiffLive() {
        $my_repath = $this->fck['re_path'];
        $diff_level_ratio =  $this->fee['s23'];  //获奖的各个层


        //uid 得奖的ID, user_id 为引发的user_id, 2为推荐奖的ACTION_TYPE
        $sql_n = "select f.* from xt_history AS h JOIN xt_fck AS f 
                  ON h.uid = f.id 
                  where h.action_type =2 and h.user_id = {$this->fck['user_id']} 
                        and f.is_pay > 0
                        group by h.uid";

        $all_rs = M()->query($sql_n);

        //$all_rs = M('fck')->where("id in (0{$my_repath}0)")->order('re_level desc,pdt desc')->select();
        foreach ($all_rs as $rs) {
            $ratio = $this->getReLevelRatio($diff_level_ratio, $rs['re_nums']);
            $this->getPriceFck = $rs;

            $remark = '直荐级差奖加单补发';
            $action = 'recomm';
            $this->type = 2;    //放到直荐级奖
            $this->awardCalculate($this->base_money, $ratio, $rs, $remark, $action);
        }
    }


    /**
     * 获取推荐人数的比率
     * @param $diff_level_ratio
     * @param $nums
     * @return int
     */
    private function getReLevelRatio($diff_level_ratio, $nums) {
        $ratio = 0;
        foreach ($diff_level_ratio as $n => $level_ratio) {
            if($nums >= $n ) $ratio = $level_ratio;
        }
        return $ratio;
    }



    /**
     * 推荐奖
     */
    public function priceRecomm(){
        $re_path = $this->fck['re_path'];
        $re_level = $this->fck['re_level'];
        $member_glevel  = $this->fee['member_glevel'];
        $agent_glevel   = $this->fee['agent_glevel'];

        $a_rs = D('Fck') ->where("is_pay = 1 and id in (0{$re_path}0) and $re_level - re_level <= {$agent_glevel}")
                              ->field('id,user_id,re_path,u_level,re_level,is_agent')->order('re_level desc')->select();
        if (!$a_rs) return false;

        foreach ($a_rs as $rs) {
            $diff_level = $re_level - $rs['re_level'];
            if($rs['is_agent'] == 0 && $diff_level > $member_glevel) continue;

            $ratio = $this->fee['invest_ratio'][$diff_level - 1];
            $this->getPriceFck = $rs;
            $this->awardCalculate($this->fck['cpzj'], $ratio);
        }
    }



    /**
     * 发放奖金，计算判断发放
     * @param $myid 得奖ID
     * @param int $inUserID 操作ID
     * @param int $bnum Fck中的innb，奖的类型
     * @param int $money_count 发放奖金金额
     * @param bool $day_lim     是否每日封顶
     * @param bool $up_time     是否更新每日封顶金额
     */
    public function award_bonus($myid, $inUserID=0, $bnum=0, $money_count=0){
        if($money_count < 0) return false;     //奖金小于0，不计算

        $money_left = $money_count;    //剩余，此值写入现金账户

        $MDFCK = D('Fck');

        $bid = $MDFCK->_getTimeTableList($myid);     //返回 Bonus表中的用户ID, 保存到Bonus,time表中
        $inbb = "b".$bnum;      //奖项的代号 b1,b2...b12


        $bonus = M('bonus');
        $bonus->execute("UPDATE __TABLE__ SET b0=b0+".$money_left."," .$inbb."=".$inbb."+".$money_count."  WHERE id={$bid}"); //加到记录表
        $MDFCK->execute("update __TABLE__ set zjj=zjj+".$money_count. ",xy_money=xy_money+".$money_count." where id=".$myid);//加到fck

        unset($bonus);

        //数据金额的保存
        if($money_count >= 0){
            $MDFCK->addencAdd($myid,$inUserID,$money_count,$bnum);
        }
        /*if($money_left >= 0){      //还有剩余金额保存在现金账户
            $this->addencAdd($myid,$inUserID,$money_left,25,0,0,0,"进入现金币账户");
        }*/

        unset($fck_rs);
    }


    /**
     * 获取全部的fee表或者其中一个,单个不用取下标
     * @param string $ratio_name_s
     * @return array|bool
     */
    public function getFeeRule($ratio_name_s='') {
        $fee = M('Fee')->field($ratio_name_s)->find();
        if(!$fee) return false;

        $rule_single = array();
        $rule_pair = array();
        foreach ($fee as $pair_name => $pair_val) {
            $rule[$pair_name] = explode("|", $pair_val);
            foreach ($rule[$pair_name] as $key=>$val) {
                $item = explode("-", $val);
                if(isset($item[1])) {   //有多个键值
                    $rule_pair[$pair_name][$item[0]] = $item[1];
                } else {    //只有单个值
                    if(count($rule[$pair_name]) == 1) {
                        $rule_single[$pair_name] = $val;
                    } else {
                        $rule_single[$pair_name] = $rule[$pair_name];
                    }
                }
            }
        }

        return array_merge($rule_single, $rule_pair);
    }

    public function sayHello() {
        echo 'hello world';
    }
}